'''
captcha
'''

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os
import requests
import time
import js_inject


# CapMonster Cloud 的 API_KEY
#API_KEY = os.getenv('CAPMONSTER_API_KEY')
API_KEY = "7b0f2915999af572c26eec84b4ec012a"
CREATE_TASK_URL = 'https://api.capmonster.cloud/createTask'
GET_TASK_RESULT_URL = 'https://api.capmonster.cloud/getTaskResult'


def create_task(website_key, context, iv, challenge_script_url, captcha_script_url,website_url):
    print("创建任务中...")
    proxies = {'https': 'http://127.0.0.1:7890'}
    task_data = {
        "clientKey": API_KEY,
        "task": {
            "type": "AmazonTaskProxyless",
            "websiteURL": website_url,  # 替换为正确的值
            "challengeScript": challenge_script_url,
            "captchaScript": captcha_script_url,
            "websiteKey": website_key,
            "context": context,
            "iv": iv,
            "cookieSolution": False  # 如果需要“aws-waf-token” cookies，设置为 True
        }
    }
    response = requests.post(CREATE_TASK_URL, json=task_data,proxies=proxies,verify=False,timeout=5)
    response.raise_for_status()
    response_json = response.json()
    if response_json['errorId'] == 0:
        print(f"任务创建成功。任务 ID: {response_json['taskId']}")
        return response_json['taskId']
    else:
        print(f"创建任务时出错: {response_json['errorCode']}")
        return None


def get_task_result(task_id):
    print("获取任务结果中...")
    proxies = {'https': 'http://127.0.0.1:7890'}
    result_data = {"clientKey": API_KEY, "taskId": task_id}
    while True:
        response = requests.post(GET_TASK_RESULT_URL, json=result_data,proxies=proxies,verify=False,timeout=5)
        response_json = response.json()
        if response_json['status'] == 'ready':
            print(f"任务结果已准备好: {response_json}")
            return response_json
        elif response_json['status'] == 'processing':
            print("任务仍在处理中...")
            time.sleep(5)
        else:
            print(f"检索任务结果时出错: {response_json['errorCode']}")
            return response_json


setup_script = """
if (!window.__urlMonitor) {
    window.__urlMonitor = { urls: new Set() };

    const originalFetch = window.fetch;
    window.fetch = function(...args) {
        const url = args[0];
        if (url) window.__urlMonitor.urls.add(url);
        return originalFetch.apply(this, args);
    };

    const originalXHR = window.XMLHttpRequest;
    window.XMLHttpRequest = function() {
        const xhr = new originalXHR();
        const originalOpen = xhr.open;
        xhr.open = function(method, url) {
            if (url) window.__urlMonitor.urls.add(url);
            return originalOpen.apply(this, arguments);
        };
        return xhr;
    };
}
return '监控器就绪';
"""

# 2. 查询函数
get_urls_script = """
return window.__urlMonitor ? Array.from(window.__urlMonitor.urls) : [];
"""


# 启动浏览器
options = webdriver.ChromeOptions()
#options.add_argument('--proxy-server=http://127.0.0.1:7890')
options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
#options.add_argument('--lang=ja-JP')
options.add_argument("--start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument("--disable-blink-features=AutomationControlled")
service = Service(executable_path="E:\deleloptool\chromedriver-win64\chromedriver.exe")
options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
driver = webdriver.Chrome(options=options,service=service)


def clear_api_responses(driver):
    """清空之前的响应记录"""
    driver.execute_script("window.__apiResponses = [];")


def get_api_responses(driver, filter_pattern=None, method_filter=None):
    """获取拦截的 API 响应"""
    all_responses = driver.execute_script("return window.__apiResponses;")

    filtered_responses = all_responses
    if filter_pattern:
        filtered_responses = [r for r in filtered_responses if filter_pattern in r['url']]
    if method_filter:
        filtered_responses = [r for r in filtered_responses if r['method'].upper() == method_filter.upper()]

    return filtered_responses



try:
    # 打开主页
    print("打开页面中...")
    driver.get('https://manatuku.com/payments/new')

    # 等待页面完全加载
    WebDriverWait(driver, 10).until(
        lambda d: d.execute_script("return document.readyState") == "complete"
    )

    # 等待gokuProps定义
    WebDriverWait(driver, 10).until(
        lambda d: d.execute_script("return typeof window.gokuProps !== 'undefined'")
    )

    captcha_params = driver.execute_script(js_inject.challenge_js)
    if captcha_params:
        print("网站密钥:", captcha_params['websiteKey'])
        print("上下文:", captcha_params['context'])
        print("IV:", captcha_params['iv'])
        print("挑战脚本:", captcha_params['challengeScriptUrl'])
        print("验证码脚本:", captcha_params['captchaScriptUrl'])

    website_key = captcha_params['websiteKey']
    context = captcha_params['context']
    iv = captcha_params['iv']
    challenge_script_url = captcha_params['challengeScriptUrl']
    captcha_script_url = challenge_script_url.replace('challenge.js', 'captcha.js').replace('token', 'captcha')

    wait = WebDriverWait(driver, 10)
    #clear_api_responses(driver)
    time.sleep(2)
    driver.execute_script(js_inject.intercept_script_improved)
    captcha_frame = wait.until(
        EC.presence_of_element_located((By.ID, "amzn-captcha-verify-button"))
         )
    captcha_frame.click()
    time.sleep(3)
    #responses = get_api_responses(driver,method_filter="get")
    responses = driver.execute_script(js_inject.get_urls_script)
    print(responses)
    if responses:
      response_json = responses[0]
      # 创建并解决 CAPTCHA 任务
      task_id = create_task(website_key, context, iv, challenge_script_url, captcha_script_url,response_json)
      if task_id:
        result = get_task_result(task_id)
        # 根据需要使用结果提交 CAPTCHA 解决方案
        if result:
            print("<UNK>")
            #wait = WebDriverWait(driver, 10)
            #captcha_frame = wait.until(
           #     EC.presence_of_element_located((By.ID, "amzn-captcha-verify-button"))
           # )
            #captcha_frame.click()
            #print("<UNK>")
    # 解决 CAPTCHA 后继续处理搜索结果
    # WebDriverWait(driver, 10).until(
    #     EC.presence_of_element_located((By.CSS_SELECTOR, 'div.locations-list'))  # 替换为正确的值
    # )


finally:
    print("<UNK>")